package com.atguigu.redis7.bitmap;

import com.atguigu.redis7.course.utils.Result;
import org.apache.commons.lang.BitField;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.BitSet;
import java.util.List;

@Component
//用户签到功能
public class SignCount {

    @Autowired
    private RedisTemplate redisTemplate;

//    @PostConstruct
    public Result signCount() {
        Long userId = 2L;  //模拟，平时要从redis获取

        LocalDateTime now = LocalDateTime.now();

        // 202303  这种格式
        String format = now.format(DateTimeFormatter.ofPattern("yyyyMM"));

        String key = "sign:" + userId + ":" + format;

        //获取当前是本月的第几天
        int dayOfMonth = now.getDayOfMonth();

        BitFieldSubCommands bitFieldSubCommands = BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0);

        List<Long> list = redisTemplate.opsForValue().bitField(key, bitFieldSubCommands);

        if (ObjectUtils.isEmpty(list)) {
            return Result.ok(0);
        }

        Long num = list.get(0);  //最低位对应着最高位


        int maxCount = 0;
        int nowCount = 0;

        while (num > 0) {
            System.out.println((num&1));
            //最后一位是1
            if ((num & 1) == 1) {
                nowCount++;//天数+1
                maxCount = Math.max(maxCount, nowCount);
            } else {
                //刷新计数  因为不连续了
                nowCount = 0;
            }
            num >>= 1;
        }

        return Result.ok(maxCount);
    }

    public Result sign() {
        Long userId = 2L;  //模拟，平时要从redis获取

        LocalDateTime now = LocalDateTime.now();

        // 202303  这种格式
        String format = now.format(DateTimeFormatter.ofPattern("yyyyMM"));

        String key = "sign:" + userId + ":" + format;

        //获取当前是本月的第几天
        int dayOfMonth = now.getDayOfMonth();

        //设置进去 bitmap是从0开始
        redisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);

        return Result.ok();
    }
}
